<template>
  <div class="profile-container">
    <!-- 基本信息 -->
    <el-card class="card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
          <el-button type="primary" size="small" @click="handleEdit">编辑</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="80px"
        :disabled="!isEditing"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :http-request="customUpload"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-error="handleAvatarError"
              >
                <el-avatar 
                  v-if="userForm.avatar" 
                  :src="userForm.avatar" 
                  :size="80"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="avatar-tip">支持jpg、jpeg、png格式，大小不超过2MB</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户ID">
              <el-input v-model="userForm.id" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="userForm.gender" placeholder="请选择性别">
                <el-option label="未知" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="region">
              <el-cascader
                v-model="userForm.region"
                :options="regionOptions"
                :props="{ expandTrigger: 'hover' }"
                placeholder="请选择所在地区"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址">
              <el-input v-model="userForm.address" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="个人简介">
              <el-input
                v-model="userForm.bio"
                type="textarea"
                :rows="3"
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 身份标签卡片后面 -->
    <el-card class="card">
      <template #header>
        <div class="card-header">
          <span>身份标签</span>
        </div>
      </template>
      <div class="role-tags">
        <div class="current-role">
          <span class="label">我的身份：</span>
          <el-tag 
            :type="getRoleTagType(userForm.role)"
            effect="dark"
            size="large"
            class="role-tag"
          >
            {{ getRoleName(userForm.role) }}
          </el-tag>
        </div>
        <div class="role-desc">
          <el-alert
            :title="getRoleDescription(userForm.role)"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>
    </el-card>

    <!-- 学生信息卡片 -->
    <el-card class="card" v-if="userForm.role === 'student'">
      <template #header>
        <div class="card-header">
          <span>学生信息</span>
          <el-button type="primary" size="small" @click="handleEditStudent">编辑</el-button>
        </div>
      </template>
      
      <el-form 
        ref="studentFormRef"
        :model="studentForm"
        label-width="100px"
        :disabled="!isEditingStudent"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="学号">
              <el-input v-model="studentForm.studentNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级">
              <el-input v-model="studentForm.grade" placeholder="请输入年级，如：2023级" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="学院">
              <el-input v-model="studentForm.college" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业">
              <el-input v-model="studentForm.major" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="班级">
              <el-input v-model="studentForm.className" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系人">
              <el-input v-model="studentForm.emergencyContact" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急电话">
              <el-input v-model="studentForm.emergencyPhone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="isEditingStudent">
          <el-button type="primary" @click="handleSubmitStudent">保存</el-button>
          <el-button @click="cancelEditStudent">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码卡片 -->
    <el-card class="card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="80px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Lock, InfoFilled, ArrowDown } from '@element-plus/icons-vue'
import { getUserInfo, updateUserProfile, uploadAvatar } from '@/api/user'
import request from '@/utils/request'
import { getStudentInfo, updateStudentInfo } from '@/api/student'

const store = useStore()
const router = useRouter()
const isEditing = ref(false)
const formRef = ref()
const passwordFormRef = ref()

// 基本信息表单
const userForm = reactive({
  id: '',
  username: '',
  realName: '',
  gender: 0,  // 默认为未知
  phone: '',
  email: '',
  avatar: '',
  region: [],
  address: '',
  bio: '',
  role: ''
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 基本信息验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  avatar: [
    { required: false, message: '请上传头像', trigger: 'change' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const regionOptions = [
  {
    value: 'guangdong',
    label: '广东省',
    children: [
      {
        value: 'guangzhou',
        label: '广州市',
        children: [
          { value: 'tianhe', label: '天河区' },
          { value: 'haizhu', label: '海珠区' },
          { value: 'liwan', label: '荔湾区' },
          { value: 'yuexiu', label: '越秀区' },
          { value: 'baiyun', label: '白云区' },
          { value: 'huangpu', label: '黄埔区' },
          { value: 'panyu', label: '番禺区' },
          { value: 'nansha', label: '南沙区' },
          { value: 'huadu', label: '花都区' },
          { value: 'zengcheng', label: '增城区' },
          { value: 'conghua', label: '从化区' }
        ]
      }
    ]
  }
]

const loadUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    console.log('用户信息:', data)
    
    // 处理角色字段
    if (data.role) {
      if (data.role.startsWith('ROLE_')) {
        data.role = data.role.substring(5) 
      }
    }

    // 处理性别字段，确保是数字类型
    if (data.gender !== undefined) {
      data.gender = Number(data.gender)
    } else {
      data.gender = 0 // 默认未知
    }

    // 处理地区字段
    if (data.region) {
      // 如果是字符串数组，直接使用
      if (Array.isArray(data.region)) {
        data.region = data.region
      }
      // 如果是字符串，尝试解析 JSON
      else if (typeof data.region === 'string') {
        try {
          const parsedRegion = JSON.parse(data.region)
          data.region = Array.isArray(parsedRegion) ? parsedRegion : []
        } catch (e) {
          console.error('解析地区数据失败:', e)
          data.region = []
        }
      }
    } else {
      data.region = []
    }

    // 处理头像字段，确保只有在有效的URL时才设置
    if (!data.avatar || data.avatar === 'undefined' || data.avatar === 'null') {
      data.avatar = ''
    }

    // 处理其他字段的默认值
    data.address = data.address || ''
    data.bio = data.bio || ''
    
    // 更新表单数据
    Object.assign(userForm, data)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 基本信息相关方法
const handleEdit = () => {
  isEditing.value = true
}

const cancelEdit = () => {
  isEditing.value = false
  loadUserInfo()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 只提取后端 DTO 支持的字段
    const formData = {
      id: userForm.id,
      username: userForm.username,
      realName: userForm.realName,
      gender: Number(userForm.gender),
      phone: userForm.phone,
      email: userForm.email,
      avatar: userForm.avatar,
      region: userForm.region,
      address: userForm.address,
      bio: userForm.bio
    }

    await store.dispatch('user/updateProfile', formData)
    ElMessage.success('保存成功')
    isEditing.value = false
    await loadUserInfo()
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error.response?.data?.msg || '保存失败')
  }
}
// 头像上传相关方法
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200 && response.data) {
    userForm.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    userForm.avatar = ''
    ElMessage.error(response.msg || '头像上传失败')
  }
}

const handleAvatarError = (error: any) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传jpg/jpeg/png格式的图片!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

// 修改密码相关方法
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    await store.dispatch('user/updatePassword', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    ElMessage.success('密码修改成功，请重新登录')
    await store.dispatch('user/logout')
    router.push('/login')
  } catch (error: any) {
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('密码修改失败')
    }
  }
}

const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 角色相关方法
const getRoleTagType = (role: string) => {
  if (!role) return 'info'
  
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'superadmin': 'danger',
    'admin': 'warning',
    'student': 'success',
    'counselor': 'primary'
  }
  return types[role.toLowerCase()] || 'info'
}

const getRoleName = (role: string) => {
  if (!role) return '未知角色'
  
  const names: Record<string, string> = {
    'superadmin': '超级管理员',
    'admin': '管理员',
    'student': '学生',
    'counselor': '咨询师'
  }
  return names[role.toLowerCase()] || '未知角色'
}

const getRoleDescription = (role: string) => {
  if (!role) return '未知角色'
  
  const descriptions: Record<string, string> = {
    'superadmin': '拥有系统最高权限，可以管理所有功能',
    'admin': '拥有系统管理权限，可以管理大部分功能',
    'student': '学生，可以使用基本功能',
    'counselor': '心理咨询师，可以提供咨询服务'
  }
  return descriptions[role.toLowerCase()] || '未知角色'
}

// 自定义上传方法
const customUpload = async (options: any) => {
  try {
    const { data } = await uploadAvatar(options.file)
    handleAvatarSuccess({ code: 200, data })
  } catch (error) {
    handleAvatarError(error)
  }
}

// 学生表单相关
const isEditingStudent = ref(false)
const studentFormRef = ref()
const studentForm = ref({
  id: '',
  userId: store.state.user.id,
  studentNo: '',
  college: '',
  major: '',
  grade: '',
  className: '',
  emergencyContact: '',
  emergencyPhone: ''
})

// 加载学生信息
const loadStudentInfo = async () => {
  try {
    const { data } = await getStudentInfo()
    studentForm.value = data || {
      userId: store.state.user.id,
      studentNo: '',
      college: '',
      major: '',
      grade: '',
      className: '',
      emergencyContact: '',
      emergencyPhone: ''
    }
  } catch (error) {
    console.error('加载学生信息失败:', error)
  }
}

// 编辑学生信息
const handleEditStudent = () => {
  isEditingStudent.value = true
}

// 取消编辑学生信息
const cancelEditStudent = () => {
  isEditingStudent.value = false
  loadStudentInfo()
}

// 提交学生信息
const handleSubmitStudent = async () => {
  try {
    await updateStudentInfo(studentForm.value)
    ElMessage.success('保存成功')
    isEditingStudent.value = false
    await loadStudentInfo()
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error.response?.data?.msg || '保存失败')
  }
}

onMounted(() => {
  loadUserInfo()
  if (store.state.user.role === 'student') {
    loadStudentInfo()
  }
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;

  .card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409EFF;
      }
    }

    .avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 80px;
      height: 80px;
      line-height: 80px;
      text-align: center;
    }
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
    
    .el-form-item__label {
      font-weight: normal;
      color: #606266;
    }
  }
}
</style> 